const api = require("../../utils/api");

var mapContext = null;
var animation = {};

Page({
    data: {
        latitude: '', //中心纬度
        longitude: '', //中心经度
        scale: 14, //缩放级别，取值范围为3-20，默认16
        myMarker: {
            id: 1,
            callout: {
                content: '我的位置',
                padding: 10,
                borderRadius: 2,
                color: '#ffffff',
                bgColor: '#00c16f',
                display: 'ALWAYS'
            },
            latitude: 22.79784,
            longitude: 108.31368,
            width: 30,
            height: 44,
        },
        markertapList: [],
        markerObj: {},

        communityRankingType: 'month',
        communityRankingList: [],

        panelAnimation: {}, //商品详情弹窗的动画效果
        isShowLayer: false, //弹窗遮罩层
    },
    onLoad(options) {
        this.initMap();
        this.checkAuth();
        this.getCommunityRankingList();
    },
    onShow() {
        //初始化动画
        animation = wx.createAnimation({
            duration: 500,
            timingFunction: 'ease-out',
        });
    },

    initMap() { //初始化地图
        mapContext = wx.createMapContext('mapId');
    },
    checkAuth() { //检查是否有位置授权
        wx.getSetting({
            success: res => {
                if (res.authSetting['scope.userLocation'] == false) {
                    wx.openSetting({
                        success(res) {
                            res.authSetting = {//打开授权位置页面，让用户自己开启
                                "scope.userLocation": true
                            }
                        }
                    });
                } else {
                    wx.authorize({
                        scope: 'scope.userLocation',
                        success: () => {
                            //获取位置后相关操作
                            this.getLocation();
                        }
                    })
                }
            }
        });
    },
    getLocation() { //获取经纬度
        wx.getLocation({
            type: 'wgs84',
            success: res => {
                console.log(res)
                this.setData({
                    latitude: res.latitude,
                    longitude: res.longitude,
                });

                let myMarker = {
                    id: 1,
                    callout: {
                        content: '我的位置',
                        padding: 10,
                        borderRadius: 2,
                        color: '#666',
                        // bgColor: '#3371fd',
                        display: 'ALWAYS'
                    },
                    latitude: this.data.latitude,
                    longitude: this.data.longitude,
                    width: 30,
                    height: 44,
                }
                this.setData({
                    myMarker: myMarker,
                });
                this.getCommunityStore();
            }
        });
    },
    getCommunityStore() { //获取店铺列表，并绘制地图
        let params = {
            // shopType: 1, //店铺类型：0普通店铺 1社区自营 2平台自营
            pageNum: 1,
            pageSize: 1000
        }
        api.post(`/index/shop/recommend`, params)
            .then(res => {
                let myMarker = this.data.myMarker;
                let markerList = [];

                res.content.forEach(item => {
                    if(item.lat) {
                        //整理营业时间
                        let businessBeginTime = item.businessBeginTime.split(':');
                        let businessEndTime = item.businessEndTime.split(':');
                        item.businessTime = businessBeginTime[0] + ':' + businessBeginTime[1] + '~' + businessEndTime[0] + ':' + businessEndTime[1];

                        markerList.push({
                            id: item.shopId,
                            shopName: item.shopName,
                            shopLogo: item.shopLogo,
                            businessTime: item.businessTime,
                            shopAddress: item.shopAddress,
                            latitude: Number(item.lat),
                            longitude: Number(item.lng),
                            // iconPath: logoPath,
                            width: 30,
                            height: 44,
                            callout: {
                                content: item.shopName,
                                color: '#ffffff',
                                bgColor: '#ffb30b',
                                padding: 10,
                                borderRadius: 2,
                                display: 'ALWAYS'
                            },
                        })
                    }
                });

                if(markerList.length > 0) {
                    let markers = markerList.concat([myMarker]);
                    mapContext.addMarkers({
                        markers: markers,
                        clear: true
                    });

                    this.setData({
                        markertapList: markerList,
                    });
                } else {
                    let markers = [myMarker];
                    mapContext.addMarkers({
                        markers: markers,
                        clear: true
                    });
                }
            })
    },

    markertap(e) { //点击地地图坐标
        console.log(e);
        const { markertapList } = this.data;
        const obj = markertapList.find((item) => {
            return item.id === e.detail.markerId;
        });
        if (obj) {
            this.setData({
                markerObj: obj
            });
            this.openMarkerDialog();
        }
    },
    openMarkerDialog() { //打开地图详情弹窗
        animation.bottom('0').step();
        this.setData({
            panelAnimation: animation.export(),
            isShowLayer: true
        });
    },
    closePanel() { //关闭地图详情弹窗
        animation.bottom('-100%').step();
        this.setData({
            panelAnimation: animation.export(),
            isShowLayer: false,
        });
    },
    gotoStore(e) {
        let item = e.currentTarget.dataset.item;
        wx.navigateTo({
            url: '/pages/storeCategory/storeCategory?id=' + item.id,
        });
        this.closePanel();
    },

    chooseRankingType(e) { //切换社区排行榜类型
        let type = e.currentTarget.dataset.type;
        this.setData({
            communityRankingType: type,
        });
        this.getCommunityRankingList();
    },
    getCommunityRankingList() { //获取社区排行榜
        api.post(`/community/commonweal/page?rankingType=${this.data.communityRankingType}`)
            .then(res => {
                this.setData({
                    communityRankingList: res.content,
                })
            })
    },
})